TOWER OF RADIOACTIVE ALLOY (ハノイの塔)
ハノイの塔。
https://gyazo.com/4415466a03663ca99dd26de4cddd534e
操作
0: マグネットをスポット0へ移動
1: スポット1へ移動
2: スポット2へ移動
3: マグネットのON/OFFを切り替える
code: 疑似コード
def hanoi(n, source, dest, work)
if n == 0
puts "move the disk(#{n}) from source(#{source}) to dest(#{dest})"
else
hanoi(n - 1, source, work, dest)
puts "move the disk(#{n}) from source(#{source}) to dest(#{dest})"
hanoi(n - 1, work, dest, source)
end
end
hanoi(3, 1, 0, 2)
code:出力結果
$ ruby hanoi.rb
move the disk(0) from source(1) to dest(2)
move the disk(1) from source(1) to dest(0)
move the disk(0) from source(2) to dest(0)
move the disk(2) from source(1) to dest(2)
move the disk(0) from source(0) to dest(1)
move the disk(1) from source(0) to dest(2)
move the disk(0) from source(1) to dest(2)
move the disk(3) from source(1) to dest(0)
move the disk(0) from source(2) to dest(0)
move the disk(1) from source(2) to dest(1)
move the disk(0) from source(0) to dest(1)
move the disk(2) from source(2) to dest(0)
move the disk(0) from source(1) to dest(2)
move the disk(1) from source(1) to dest(0)
move the disk(0) from source(2) to dest(0)
code:hanoi
const add 0
const add_ri 64
const add_ii 192
const sub 1
const sub_ri 65
const jeq 32
const jeq_ri 96
const jeq_ii 224
const jlt 34
const jlte 35
const jgt 36
const jgte 37
const jgte_ri 101
const sw 16
const sw_ri 80
const lw 17
const lw_ri 81
const call 8
const ret 9
const r0 0
const r1 1
const r2 2
const r3 3
const r4 4
const r5 5
const sp 5
const sp_offset 4
const counter 6
const input 7
const output 7
const _ 0
const n 1
const src 2
const dst 3
const work 4
const toggle_magnet 5
# init
add input _ n
add input _ src
add input _ dst
add input _ work
call sp _ hanoi
label loop
jeq r0 r0 loop
### hanoi
label hanoi
jeq n r0 n_eq_zero
## n!=0
sub_ri sp 4 sp
sw_ri sp 0 n
sw_ri sp 1 src
sw_ri sp 2 dst
sw_ri sp 3 work
# hanoi(n-1, source, work, dest)
sub_ri n 1 n
lw_ri sp 3 dst # dst <= work
lw_ri sp 2 work # work <= dst
call sp _ hanoi
# move panel
lw_ri sp 0 n
lw_ri sp 1 src
lw_ri sp 2 dst
lw_ri sp 3 work
# move magnet to src
add src r0 output
# magnet on
add_ii toggle_magnet 0 output
# move magnet to dst
add dst r0 output
# magnet off
add_ii toggle_magnet 0 output
# hanoi(n-1, work, dest, source)
sub_ri n 1 n
lw_ri sp 3 src # src <= work
lw_ri sp 2 dst # dest <= dest
lw_ri sp 1 work # work <= source
call sp _ hanoi
add_ri sp 4 sp
jeq r0 r0 hanoi_return
label n_eq_zero
## n==0
# move magnet to src
add src r0 output
# magnet on
add_ii toggle_magnet 0 output
# move magnet to dst
add dst r0 output
# magnet off
add_ii toggle_magnet 0 output
label hanoi_return
ret sp _ _